#include <ESP8266WiFi.h>//安装esp8266arduino开发环境
#include <Wire.h>  //声明I2C库文件
#include <AliyunIoTSDK.h>//引入阿里云 IoT SDK
//需要安装crypto库、PubSubClient库
static WiFiClient espClient;
#define PRODUCT_KEY "gdb9d8QpRRe"
#define DEVICE_NAME "test02"
#define DEVICE_SECRET "ead60e25a653b904735d29f2cb736d10"
#define REGION_ID "cn-shanghai"
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID         "esp8266test"
#define WIFI_PASSWD       "qwertyui"
unsigned long lastMsMain;

void setup()
{ 
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);

  //连接到wifi
  wifiInit(WIFI_SSID, WIFI_PASSWD);

  //初始化 iot，需传入 wifi 的 client，和设备产品信息
  AliyunIoTSDK::begin(espClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, REGION_ID);

  //绑定一个设备属性回调，当远程修改此属性，会触发LED函数
  AliyunIoTSDK::bindData("Brightness", LED);//主机的板载LED
  Wire.begin(); // 加入 i2c 总线，作为主机
}
//-------------------------------------------------------------------------
void loop()
{ 
  AliyunIoTSDK::loop();//必要函数

  if (millis() - lastMsMain >= 2000)//每2秒发送一次
  { 
    lastMsMain = millis();
    AliyunIoTSDK::send("CurrentHumidity", 50);
  }
}
//wifi 连接-----------------------------------------------------------------
void wifiInit(const char *ssid, const char *passphrase)
{ 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, passphrase);
  while (WiFi.status() != WL_CONNECTED)
  { 
    delay(1000);
    Serial.println("WiFi not Connect");
  }
  Serial.println("Connected to AP");
}
//主机板载灯控制函数（阿里云端修改LED属性时触发）-------------------------------------------------------
void LED(JsonVariant L)//固定格式，修改参数L
{ 
  int Brightness = L["Brightness"];//参数传入（LED）
  if (Brightness == 0)
  { 
    digitalWrite(LED_BUILTIN, HIGH);
  }
  else 
  { 
    digitalWrite(LED_BUILTIN, LOW);
  }
  Serial.printf("收到的LED是："); Serial.println(Brightness);
}